package com.zscat.mallplus.qsg.impl;

import com.alibaba.fastjson.JSONObject;
import com.zscat.mallplus.vo.CountDownObj;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MqttMessageCallback implements MqttCallback {
    @Override
    public void connectionLost(Throwable throwable) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //接收到数据后，通过闭锁释放阻塞的线程，同时设置结果返回给调用者
        log.info("接收消息主题:{}" , topic);
        log.info("接收消息内容:{} ", new String(message.getPayload()));
        ConcurrentHashMap<String, CountDownObj> countDownLatchMap = ChannelMap.getChannelMap();
        String deviceCode = StringUtils.substring(topic,10);
        CountDownObj countDownObj=countDownLatchMap.get(deviceCode);
        if(countDownObj != null) {
            String returnMessage = new String(message.getPayload());
            JSONObject returnJson = JSONObject.parseObject(returnMessage);
            JSONObject returnBody = returnJson.getJSONObject("Body");
            JSONObject returnInfo = returnBody.getJSONObject("Info");
            String cmd = returnInfo.getString("Cmd");
            //如果是发送的缺球检查命令获取对应的检查结果
            if("Check".equalsIgnoreCase(cmd)){
                Integer checkStatus = returnInfo.getJSONObject("Msg").getInteger("Pass");
                countDownObj.setValue(checkStatus);
                countDownObj.getCountDownLatch().countDown();
            }
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
